/**
 * DateConverter.java
 * Product:BaseLayer
 * Version:1.0
 * Copyright 2009 by DNE
 * All Rights Reserved.
 */
package com.site.util.base.converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;

import com.site.util.DateUtils;
import com.site.util.StringUtils;

/**
 * Struts2类型转换器
 * 重写日期类型转换器，是为了按照指定的日期格式在页面上显示日期对象
 */
public class DateTypeConverter extends StrutsTypeConverter {
	private final String FORMAT="yyyy-MM-dd HH:mm:ss";
	/* (non-Javadoc)
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertFromString(java.util.Map, java.lang.String[], java.lang.Class)
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Date date=null;
		String dateString=null;
		if(values!=null&&values.length>0){
			dateString=values[0];
			if(!StringUtils.isEmpty(dateString)){
				if(dateString.indexOf(" ")==-1){
					dateString+=" 00:00:00";
				}
				// 没有秒的情况
				if(dateString.length() == 16){
					dateString+=":00";
				}
				DateFormat formater=new SimpleDateFormat(FORMAT);
				try {
					date=formater.parse(dateString);
				} catch (ParseException e) {
					e.printStackTrace();
					throw new IllegalArgumentException(e);
				}
			}
		}
		return date;
	}

	/* (non-Javadoc)
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertToString(java.util.Map, java.lang.Object)
	 */
	@Override
	public String convertToString(Map context, Object date) {
		if(date!=null){
			return DateUtils.formatDate((Date)date, FORMAT);
		}
		return null;
	}

}
